import React from 'react';
import {
    View,
    Text,
    FlatList,
    TouchableOpacity,
    Dimensions,
    Image, TextInput,
} from 'react-native';
import styles from './styles';
import NavigationBar from '../../common/NavigationBar';
import {BASE_URL} from '../../common/BASE_URL';
import HttpUtils from '../../expand/dao/HttpUtils';
import {Constant, StylesConstant} from '../../common/Constant';
import StorageUtil from '../../utils/StorageUtil';
import NavigationUtil from '../../navigators/NavigationUtil';
import Utils from '../../utils/Utils';
import GlobalStyles from '../../common/styles/GlobalStyles';
import {Tabs} from '@ant-design/react-native';
import ToastUtil from '../../utils/ToastUtil';
import EnterpriseItem from './components/EnterpriseItem';
import FontAwesome from "react-native-vector-icons/FontAwesome";

let current = 1;
let total = 0;
const size = 10;

// 法人单位列表
const getEnterpriseUrl = BASE_URL.apiBaseUrl + '/app/legalPerson'

export default class Enterprise extends React.Component {
    constructor(props) {
        super(props);
        // 获取参数
        this.state = {
            isLoading: false, // list加载状态
            hideLoadingMore: false,
            dataList: [{id:1},{id:2},{id: 3}],
            dataList2: [],
            enterpriseList: [],
            query: {
                // current: 1, // 当前页数
                // size: 10, // 每页大小
                queryStr: '', // 模糊查询
            },
        };
    }

    componentDidMount() {
        this.loadData();
    }

    loadData(loadMore) {
        if(this.state.isLoading) return
        let params = {size: size, page: current} // sort: 'applicationTime,desc'
        const bool = this.isLoadMore(loadMore); // 4.的判断是否需要加载更多
        if(bool){
            // const key = ToastUtil.loading('加载中...')
            HttpUtils.request({
                url: getEnterpriseUrl,
                params
            }).then(res=>{
                console.log(res)
                // ToastUtil.remove(key)
                const {content, totalElements} = res
                const data = {
                    enterpriseList: loadMore
                        ? this.state.enterpriseList.concat(content)
                        : content,
                }
                // 如果当前查询的是最后一页，则更新FlatList底部控制器的文字，显示没有更多数据
                const totalPage = parseInt(((totalElements-1)/size))
                total = totalPage;
                if (current == totalPage) {
                    data.hideLoadingMore = true;
                }
                // 如果当前查询的是第一页，但是没有查出数据，给出提示，并修改底部文字
                if (current == 0 && content.length === 0) {
                    data.hideLoadingMore = true;
                    ToastUtil.info('没找到相关数据');
                }
                this.setState({
                    isLoading: false,
                    ...data
                })
            }).catch(e=>{
                // ToastUtil.remove(key)
                // console.log(e);
                this.setState({
                    isLoading: false
                })
            })
        }
    }
    // 初始化数据
    async initDriverList() {
        const code = await StorageUtil.get(Constant.companyCode);
        if (code) {
            this.setState({
                isLoading: true,
            });
            HttpUtils.request({
                // url: URL,
                type: 'post',
                data: {companyCode: code, type: this.state.type},
            })
                .then((result) => {
                    const data = result.data;
                    this.setState({
                        dataList: data,
                        isLoading: false,
                    });
                })
                .catch((_) => {
                    this.setState({
                        isLoading: false,
                    });
                });
        }
    }


    render() {
        const {navigation} = this.props;
        return (
            <View style={GlobalStyles.pageContainer}>
                {/* 自定义顶部导航条 */}
                <NavigationBar
                    navigation={navigation}
                    headerBackTitle={'企业监管'}
                />

                <View style={{flex: 1}}>
                    <View style={{backgroundColor: '#fff',borderTopWidth: 1,borderColor: '#eee'}}>
                        {this._renderHeaderSearch()}
                    </View>
                    <View style={{paddingTop: 10,paddingBottom: 20}}>
                        {this._renderDataList()}
                    </View>
                </View>
            </View>
        );
    }
    _renderHeaderSearch(){
        return (
            <View style={[GlobalStyles.searchInputContainer,{paddingLeft: 10}]}>
                <TextInput
                    style={[GlobalStyles.searchIpt]}
                    ref="input"
                    multiline={false}
                    placeholder={'请输入关键字检索'}
                    onChangeText={(text) => {
                        this.setState({
                            query: {
                                ...this.state.query,
                                queryStr: text
                            },
                        });
                    }}
                />
                <TouchableOpacity
                    style={{flex: 1,marginRight: 5,alignItems: 'center'}}

                >
                    <View style={{flexDirection: 'row',alignItems: 'center'}}>
                        <FontAwesome name={'search'} size={16} color={StylesConstant.themeIconColor}/>
                        <Text style={{color: StylesConstant.themeIconColor,fontSize: 14,paddingLeft: 5}}>地图检索</Text>
                    </View>
                </TouchableOpacity>
            </View>
        )
    }
    _renderDataList(){
        const {enterpriseList, isLoading} = this.state;
        return (
            <FlatList
                style={styles.list}
                data={enterpriseList}
                keyExtractor={(item, index) => `legal_${index}`}
                renderItem={(data) => this._renderItem(data)}
                refreshControl={Utils.renderRefreshControl('加载中', isLoading, () => {
                    this.loadData();
                })}
                ListFooterComponent={() => this.genIndicator()}
                onEndReached={() => {
                    setTimeout(() => {
                        if (this.canLoadMore) {
                            this.loadData(true);
                            this.canLoadMore = false;
                        }
                    }, 100);
                }}
                onEndReachedThreshold={0.5}
                onMomentumScrollBegin={() => {
                    this.canLoadMore = true;
                }}
            />
        );
    }


    _renderItem(data){
        const {item} = data;
        return (
            <EnterpriseItem
                item={item}
                handleCallback={() => {
                    NavigationUtil.goPage('EnterpriseDetail', {
                        detail: item,
                    });
                }}
            />
        );
    }

    genIndicator() {
        const {hideLoadingMore} = this.state;
        return hideLoadingMore
            ? Utils.renderNoDataBottom()
            : Utils.renderLoadingMore();
    }

    getListBottom(isLoading, data) {
        return !isLoading && data && data.length === 0
            ? Utils.renderNoDataBottom()
            : null;
    }
    isLoadMore(loadMore) {
        // 如果触发了加载更多，但是当前页数 === 总页数，做出提示，终止该函数运行
        if (loadMore && current == total) {
            ToastUtil.info('没有更多了'); // 弹框提示
            // 修改FlatList控制器的底部显示
            this.setState({
                hideLoadingMore: true,
            });
            return false;
        }
        // 如果需要加载更多，自动翻页
        if (loadMore) {
            current++;
        } else {
            // 反之表示数据初始化，当前页重设为第一页，并修改FlatList底部控制器的文字，显示为正在加载...
            current = 0;
            this.setState({
                hideLoadingMore: false,
            });
        }
        return true;
    }
}
